<template>
  <lay-layer
    v-model="visible"
    :title="`SKU管理 - ${productData?.name || ''}`"
    :area="['95%', '85%']"
    :maxmin="true"
    :resize="true"
    @close="handleClose"
  >
    <div class="sku-dialog">
      <!-- 商品信息概览 -->
      <div class="product-overview">
        <div class="product-info">
          <div class="product-image">
            <img 
              v-if="productData?.images && productData.images.length > 0" 
              :src="productData.images[0]" 
              :alt="productData.name"
            />
            <div v-else class="no-image">暂无图片</div>
          </div>
          <div class="product-details">
            <h3 class="product-name">{{ productData?.name }}</h3>
            <p class="product-subtitle">{{ productData?.subtitle }}</p>
            <div class="product-meta">
              <span class="meta-item">SPU: {{ productData?.spuCode }}</span>
              <span class="meta-item">分类: {{ productData?.category?.name }}</span>
              <span class="meta-item">品牌: {{ productData?.brand?.name }}</span>
            </div>
          </div>
        </div>
        <div class="sku-summary">
          <div class="summary-item">
            <div class="summary-number">{{ skuStats.total }}</div>
            <div class="summary-label">总SKU数</div>
          </div>
          <div class="summary-item">
            <div class="summary-number">{{ skuStats.active }}</div>
            <div class="summary-label">启用</div>
          </div>
          <div class="summary-item">
            <div class="summary-number">{{ skuStats.inactive }}</div>
            <div class="summary-label">禁用</div>
          </div>
          <div class="summary-item">
            <div class="summary-number">{{ skuStats.lowStock }}</div>
            <div class="summary-label">库存不足</div>
          </div>
        </div>
      </div>

      <!-- 操作工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <lay-button type="primary" @click="handleAdd">
            <lay-icon type="layui-icon-add-1"></lay-icon>
            新增SKU
          </lay-button>
          <lay-button 
            type="danger" 
            :disabled="selectedRowKeys.length === 0"
            @click="handleBatchDelete"
          >
            <lay-icon type="layui-icon-delete"></lay-icon>
            批量删除 ({{ selectedRowKeys.length }})
          </lay-button>
          <lay-button @click="handleRefresh">
            <lay-icon type="layui-icon-refresh"></lay-icon>
            刷新
          </lay-button>
          <lay-button @click="handleBatchEdit" :disabled="selectedRowKeys.length === 0">
            <lay-icon type="layui-icon-edit"></lay-icon>
            批量编辑
          </lay-button>
        </div>
        <div class="toolbar-right">
          <lay-input 
            v-model="searchForm.keyword" 
            placeholder="搜索SKU编码或规格"
            style="width: 220px; margin-right: 10px;"
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <lay-icon type="layui-icon-search" @click="handleSearch"></lay-icon>
            </template>
          </lay-input>
          <lay-select 
            v-model="searchForm.status" 
            placeholder="状态筛选"
            style="width: 120px; margin-right: 10px;"
            @change="handleSearch"
          >
            <lay-select-option value="">全部状态</lay-select-option>
            <lay-select-option :value="1">启用</lay-select-option>
            <lay-select-option :value="0">禁用</lay-select-option>
          </lay-select>
          <lay-select 
            v-model="searchForm.stockStatus" 
            placeholder="库存状态"
            style="width: 120px;"
            @change="handleSearch"
          >
            <lay-select-option value="">全部库存</lay-select-option>
            <lay-select-option value="normal">正常</lay-select-option>
            <lay-select-option value="low">库存不足</lay-select-option>
            <lay-select-option value="out">缺货</lay-select-option>
          </lay-select>
        </div>
      </div>

      <!-- SKU表格 -->
      <div class="table-container">
        <lay-table 
          :columns="columns" 
          :data-source="tableData"
          :loading="loading"
          v-model:selectedKeys="selectedRowKeys"
          :default-toolbar="true"
          :pagination="false"
          :scroll="{ x: 1200 }"
        >
          <template #images="{ row }">
            <div class="sku-images">
              <div class="image-gallery">
                <img 
                  v-for="(image, index) in (row.images || []).slice(0, 3)" 
                  :key="index"
                  :src="image" 
                  :alt="`SKU图片${index + 1}`"
                  class="sku-image"
                  @click="previewImage(image)"
                />
                <div v-if="(row.images || []).length > 3" class="more-images">
                  +{{ (row.images || []).length - 3 }}
                </div>
              </div>
              <div v-if="!row.images || row.images.length === 0" class="no-image">
                暂无图片
              </div>
            </div>
          </template>

          <template #skuInfo="{ row }">
            <div class="sku-info">
              <div class="sku-code">{{ row.skuCode }}</div>
              <div class="sku-name">{{ row.name || '默认SKU' }}</div>
            </div>
          </template>

          <template #specifications="{ row }">
            <div class="specifications">
              <lay-tag 
                v-for="(value, key) in row.specifications" 
                :key="key"
                size="xs"
                type="primary"
                style="margin: 2px;"
              >
                {{ key }}: {{ value }}
              </lay-tag>
              <span v-if="!row.specifications || Object.keys(row.specifications).length === 0" class="no-spec">
                无规格
              </span>
            </div>
          </template>

          <template #priceInfo="{ row }">
            <div class="price-info">
              <div class="current-price">¥{{ row.price }}</div>
              <div v-if="row.originalPrice && row.originalPrice > row.price" class="original-price">
                ¥{{ row.originalPrice }}
              </div>
              <div v-if="row.costPrice" class="cost-price">
                成本: ¥{{ row.costPrice }}
              </div>
            </div>
          </template>

          <template #stockInfo="{ row }">
            <div class="stock-info">
              <div class="stock-quantity" :class="getStockClass(row.stockQuantity)">
                {{ row.stockQuantity }}
              </div>
              <div class="stock-warning" v-if="row.lowStockThreshold">
                预警: {{ row.lowStockThreshold }}
              </div>
            </div>
          </template>

          <template #status="{ row }">
            <lay-switch 
              v-model="row.status" 
              :value="1"
              :unvalue="0"
              @change="handleStatusChange(row)"
            ></lay-switch>
          </template>

          <template #createdAt="{ row }">
            <div class="created-time">
              {{ row.createdAt }}
            </div>
          </template>

          <template #action="{ row }">
            <div class="action-buttons">
              <lay-button size="xs" @click="handleEdit(row)">编辑</lay-button>
              <lay-button size="xs" @click="handleCopy(row)">复制</lay-button>
              <lay-button size="xs" type="danger" @click="handleDelete(row)">删除</lay-button>
            </div>
          </template>
        </lay-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <lay-page 
          v-model="pagination.current"
          :total="pagination.total"
          :limit="pagination.pageSize"
          :show-count="true"
          :show-page="true"
          :show-limit="true"
          :show-skip="true"
          @change="handlePageChange"
          @limit="handlePageSizeChange"
        ></lay-page>
      </div>
    </div>

    <!-- SKU编辑弹窗 -->
    <SkuEditDialog 
      v-model:visible="editDialogVisible"
      :sku-data="currentSku"
      :product-data="productData"
      :mode="editMode"
      @success="handleEditSuccess"
    />
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { layer } from '@layui/layui-vue'
import SkuEditDialog from './SkuEditDialog.vue'
import { productApi } from '../../../../api/module/product'

interface Props {
  visible: boolean
  productData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const editDialogVisible = ref(false)
const editMode = ref<'add' | 'edit'>('add')
const currentSku = ref<any>(null)
const selectedRowKeys = ref<string[]>([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  stockStatus: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])

// SKU统计数据
const skuStats = computed(() => {
  const total = tableData.value.length
  const active = tableData.value.filter(item => item.status === 1).length
  const inactive = tableData.value.filter(item => item.status === 0).length
  const lowStock = tableData.value.filter(item => 
    item.stockQuantity <= (item.lowStockThreshold || 10)
  ).length
  
  return { total, active, inactive, lowStock }
})

// 表格列配置
const columns = [
  {
    title: 'SKU图片',
    key: 'images',
    customSlot: 'images',
    width: '120px',
    fixed: 'left'
  },
  {
    title: 'SKU信息',
    key: 'skuInfo',
    customSlot: 'skuInfo',
    width: '180px',
    fixed: 'left'
  },
  {
    title: '规格属性',
    key: 'specifications',
    customSlot: 'specifications',
    width: '200px'
  },
  {
    title: '价格信息',
    key: 'priceInfo',
    customSlot: 'priceInfo',
    width: '120px'
  },
  {
    title: '库存信息',
    key: 'stockInfo',
    customSlot: 'stockInfo',
    width: '100px'
  },
  {
    title: '状态',
    key: 'status',
    customSlot: 'status',
    width: '80px'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: '150px',
    customSlot: 'createdAt'
  },
  {
    title: '操作',
    key: 'action',
    customSlot: 'action',
    width: '150px',
    fixed: 'right'
  }
]

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 获取库存状态样式
const getStockClass = (quantity: number) => {
  if (quantity <= 0) return 'stock-out'
  if (quantity <= 10) return 'stock-low'
  return 'stock-normal'
}

// 获取SKU列表
const getSkuList = async () => {
  if (!props.productData?.id) return
  
  loading.value = true
  try {
    const params = {
      productId: props.productData.id,
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status,
      stockStatus: searchForm.stockStatus
    }
    
    const response = await productApi.getProductSkus(props.productData.id, params)
    if (response.code === 200) {
      let rawData = []
      
      // 适配API返回的数据格式
      if (Array.isArray(response.data)) {
        // 如果返回的是数组，直接使用
        rawData = response.data
        pagination.total = response.data.length
      } else if (response.data && typeof response.data === 'object') {
        // 如果返回的是对象，尝试获取list和total字段
        rawData = response.data.list || response.data.data || []
        pagination.total = response.data.total || response.data.count || rawData.length
      } else {
        rawData = []
        pagination.total = 0
      }
      
      // 处理数据字段映射
      tableData.value = rawData.map(item => ({
        ...item,
        // 将单个image字段转换为images数组
        images: item.image ? [item.image] : (item.images || []),
        // 确保价格字段为数字类型
        price: parseFloat(item.price) || 0,
        originalPrice: parseFloat(item.originalPrice) || 0,
        costPrice: parseFloat(item.costPrice) || 0,
        // 确保库存字段为数字类型
        stockQuantity: parseInt(item.stockQuantity) || 0,
        lowStockThreshold: parseInt(item.lowStockThreshold) || 10,
        // 格式化创建时间
        createdAt: item.createdAt ? new Date(item.createdAt).toLocaleString() : ''
      }))
    }
  } catch (error) {
    console.error('获取SKU列表失败:', error)
    layer.msg('获取SKU列表失败', { icon: 2 })
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getSkuList()
}

// 刷新
const handleRefresh = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    stockStatus: ''
  })
  pagination.current = 1
  getSkuList()
}

// 新增SKU
const handleAdd = () => {
  currentSku.value = null
  editMode.value = 'add'
  editDialogVisible.value = true
}

// 编辑SKU
const handleEdit = (row: any) => {
  currentSku.value = row
  editMode.value = 'edit'
  editDialogVisible.value = true
}

// 复制SKU
const handleCopy = (row: any) => {
  const copyData = { ...row }
  delete copyData.id
  delete copyData.skuCode
  currentSku.value = copyData
  editMode.value = 'add'
  editDialogVisible.value = true
}

// 批量编辑
const handleBatchEdit = () => {
  layer.msg('批量编辑功能开发中...', { icon: 3 })
}

// 预览图片
const previewImage = (imageUrl: string) => {
  layer.photos({
    photos: {
      data: [{ src: imageUrl }]
    }
  })
}

// 状态切换
const handleStatusChange = async (row: any) => {
  try {
    await productApi.updateProductSku(props.productData.id, row.id, { status: row.status })
    layer.msg('状态更新成功', { icon: 1 })
  } catch (error) {
    console.error('更新状态失败:', error)
    layer.msg('更新状态失败', { icon: 2 })
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 删除SKU
const handleDelete = (row: any) => {
  layer.confirm(`确定要删除SKU "${row.skuCode}" 吗？`, {
    title: '确认删除',
    icon: 3
  }, async () => {
    try {
      await productApi.deleteProductSku(props.productData.id, row.id)
      layer.msg('删除成功', { icon: 1 })
      getSkuList()
      emit('success')
    } catch (error) {
      console.error('删除失败:', error)
      layer.msg('删除失败', { icon: 2 })
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) return
  
  layer.confirm(`确定要删除选中的 ${selectedRowKeys.value.length} 个SKU吗？`, {
    title: '确认批量删除',
    icon: 3
  }, async () => {
    try {
      await productApi.batchDeleteProductSkus(props.productData.id, selectedRowKeys.value)
      layer.msg('批量删除成功', { icon: 1 })
      selectedRowKeys.value = []
      getSkuList()
      emit('success')
    } catch (error) {
      console.error('批量删除失败:', error)
      layer.msg('批量删除失败', { icon: 2 })
    }
  })
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.current = page
  getSkuList()
}

// 每页数量变化
const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  getSkuList()
}

// 编辑成功回调
const handleEditSuccess = () => {
  getSkuList()
  emit('success')
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal && props.productData?.id) {
    getSkuList()
  }
})
</script>

<style scoped>
.sku-dialog {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 商品概览区域 */
.product-overview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.product-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 16px;
  border: 1px solid #e0e0e0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
  font-size: 12px;
}

.product-details {
  flex: 1;
}

.product-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.product-subtitle {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.product-meta {
  display: flex;
  gap: 16px;
}

.meta-item {
  font-size: 12px;
  color: #999;
}

.sku-summary {
  display: flex;
  gap: 24px;
}

.summary-item {
  text-align: center;
}

.summary-number {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 4px;
}

.summary-label {
  font-size: 12px;
  color: #666;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

/* 表格容器 */
.table-container {
  flex: 1;
  overflow: hidden;
}

/* SKU图片 */
.sku-images {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-gallery {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.sku-image {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid #e0e0e0;
  cursor: pointer;
  transition: transform 0.2s;
}

.sku-image:hover {
  transform: scale(1.1);
}

.more-images {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #666;
  border: 1px solid #e0e0e0;
}

/* SKU信息 */
.sku-info {
  text-align: left;
}

.sku-code {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.sku-name {
  font-size: 12px;
  color: #666;
}

/* 规格属性 */
.specifications {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.no-spec {
  color: #999;
  font-size: 12px;
}

/* 价格信息 */
.price-info {
  text-align: right;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #ff4d4f;
  margin-bottom: 2px;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
  margin-bottom: 2px;
}

.cost-price {
  font-size: 12px;
  color: #666;
}

/* 库存信息 */
.stock-info {
  text-align: center;
}

.stock-quantity {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 2px;
}

.stock-normal {
  color: #52c41a;
}

.stock-low {
  color: #faad14;
}

.stock-out {
  color: #ff4d4f;
}

.stock-warning {
  font-size: 10px;
  color: #999;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

/* 分页 */
.pagination-wrapper {
  padding: 16px 0;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: center;
}
</style>